
import Vuex from 'vuex'
//引入router
import router from '@/router/index'
//使用vuex进行持久化
import persistedState from 'vuex-persistedstate'
const getObjArray = (list) => {
    let avg = []//新{id:[[1,avg],[2,avg]]}
    let newAvg = []//放单个的avg
    let oldAvg = []//原来的avg
    if (list.length === 0) return { avg, oldAvg }
    for (const item of list) {
        newAvg = [...newAvg, ...item.property]
        oldAvg.push(item.property)
    }
    let newObj = {}
    for (let item of newAvg) {
        //keys这个是里面的id 数据加工的id
        let keys = Object.keys(item)[0]
        if (Object.keys(newObj).indexOf(keys) == -1) {
            newObj[keys] = []
        }
        newObj[keys].push(item[keys])
    }
    if (Object.keys(newObj).length) {
        avg.push(newObj)
    }
    return {
        avg,
        oldAvg
    }
}
export default new Vuex.Store({
    state: {
        token: "",//token
        activeName: '',
        list: [], // { name, title, path... } 子项 $route
        alive_list: [], // 缓存得页面
        lines: [],//svg线
        tableData: [],//存表格数据
        historys: [],//存撤销历史后的平均值    这边是开始定义的数据
        avg: [],//存avg
        oldAvg: [],//存avg
        averageValue: [],//平均值
        newAvg: []
    },
    mutations: {
        //存token
        updateToken(state, data) {
            state.token = data
        },
        //删除token
        reset(state) {
            state.token = ""
        },
        //存svg
        updateLines(state, data) {
            state.lines = data
        },
        //清空svg
        resetLines(state) {
            state.lines = []
        },
        //存平均值
        setaverageValue(state, data) {
            state.averageValue = data
        },
        //更新历史
        avergehisd(state, data) {
            state.historys.push(data) // 
            const { avg, oldAvg } = getObjArray(state.historys)
            state.avg = avg
            state.oldAvg = oldAvg
        },
        //更新avg历史
        // avergeavgd(state, data) {
        //     state.oldAvg.push(data) // 将当前状态存入历史记录
        //     const { avg, oldAvg } = getObjArray(state.historys)
        //     state.avg = avg
        // },
        //撤销avg历史
        avergeavgdel(state, data) {
            const { avg, oldAvg } = getObjArray(state.historys)
            state.avg = avg
            state.oldAvg = data // 将当前avg状态存入历史记录
        },
        //撤销平均值
        averageDel(state, data) {
            state.historys = data
        },
        //存表格数据
        setTableData(state, data) {
            state.tableData = data
        },
        // 切换活动的tag
        changeTabsName(state, data) {
            state.activeName = data
            localStorage.setItem("activeName", JSON.stringify(data));
        },
        // 清空所有tag
        emptyTabs(state) {
            state.list = []
        },
        // 添加一个新tage
        changeTabs(state, data) {
            if (!data.meta.keepAlive) return
            state.activeName = data.name == 'PgIframe' ? data.params.url : data.name

            if (!state.list.length) {
                if (data.name == 'PgIframe') {
                    let add = JSON.parse(localStorage.getItem('content'));
                    add.forEach(element => {
                        console.log(element.id, data.params.url)
                        if (element.id === data.params.url) {
                            state.list.push({
                                name: data.params.url,
                                title: element.name,
                                path: data.fullPath,
                                ids: element.id,
                            })
                        }
                    });
                    return;
                }
                state.list.push({
                    name: data.name,
                    title: data.meta.title,
                    path: data.fullPath
                })
                // console.log(state.list);
            }
            else {
                // console.log(state.list)
                let flag = false
                state.list.some((item) => {
                    if (item.path == data.fullPath) {
                        flag = true
                        return true
                    }
                    return false
                })
                if (!flag) {
                    if (data.name == 'PgIframe') {
                        let add = JSON.parse(localStorage.getItem('content'));
                        add.forEach(element => {
                            if (element.id == data.params.url) {
                                state.list.push({
                                    name: data.params.url,
                                    title: element.name,
                                    path: data.fullPath,
                                    ids: element.id,
                                })
                            }
                        });
                        return;
                    }
                    state.list.push({
                        name: data.name,
                        title: data.meta.title,
                        path: data.fullPath
                    })
                }
            }
            state.alive_list = state.list.map(item => item.name)
            // console.log('====', state.list)
        },
        // 删除一个tag
        del_tabs(state, data) { // state:变量，data:新值
            // console.log(data);
            const index = state.list.findIndex((item) => item.name == data)
            // console.log(index);
            if (index != -1) {
                state.list.splice(index, 1)
                router.push('/')//跳转到首页
            }
            state.alive_list = state.list.map(item => item.name)
        },
        //根据后端存的avg调用
        setNewAvg(state, data) {
            state.newAvg = data
        },
        //清空newavg
        resetnewAvg(state) {
            state.newAvg = []
        },
        //清空oldAvg
        resetoldAvg(state) {
            state.oldAvg = []
        }
    },
    getters: {},
    actions: {
        //撤销
        setAverageDel({ commit }, data) {
            return new Promise((resolve) => {
                // 数组 【a,b,c】
                // 【a】只要一项就返回源数据tableData,
                // [a,b] 长度大于1就执行以下方法
                if (this.state.historys.length > 1) {
                    this.state.historys.pop()  //删除最后一项返回 最后一项【c】
                    this.state.oldAvg.pop()
                    const len = this.state.historys.length
                    resolve(this.state.historys[len - 1].list)  //删除最后一项的前一项【b】
                    // debugger
                    commit('averageDel', this.state.historys)
                    commit('avergeavgdel', this.state.oldAvg)
                } else {
                    commit('averageDel', [])
                    commit('avergeavgdel', [])
                    resolve(JSON.parse(JSON.stringify(this.state.tableData)))
                }
            })
        },
        //重置
        reseAverageDel({ commit }, data) {
            return new Promise((resolve) => {
                // 数组 【a,b,c】
                // 【a】只要一项就返回源数据tableData,
                // [a,b] 长度大于1就执行以下方法
                commit('averageDel', [])
                commit('avergeavgdel', [])
                resolve(JSON.parse(JSON.stringify(this.state.tableData)))
            })
        },
        //执行存后台的avg
        setAvgdatas({ commit }, datas) {
            let data = this.state.newAvg
            if (data.length == 0) return
            let _values = []
            let _index = []
            for (let item of data) {
                console.log(data);
                _values = Object.values(item)
                for (let items of _values) {

                    for (let its of items) {
                        // console.log(its[0]);
                        _index.push(its[0])
                    }
                }
            }
            const _data = datas ?? this.state.tableData
            for (let item of _data) {
                let keys = Object.keys(item)
                // console.log(keys, _index)
                for (let [index, it] of keys.entries()) {
                    if (item[it] == null && _index.includes(index)) {
                        item[it] = this.state.averageValue[index]
                    }
                }
            }
            return new Promise((resolve) => {
                resolve(_data)
            })
        },
        //接受传递的数据
        setnewAvgdatas({ commit }, data) {
            commit('setNewAvg', data)
        }
    },
    plugins: [persistedState()]
})